<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://hyperf.wiki
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 */
namespace App\Controller\Auth;

use App\Ability\ApiResponse;
use App\Achieve\User;
use App\Controller\AbstractController;
use App\Logic\AbstractLogic;
use App\Logic\User\UserLoginLogic;
use App\Rpc\UserLoginServiceInterface;
use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\Validation\ValidatorFactory;
use HyperfExt\Jwt\JwtFactory;

class PhoneController extends AbstractController
{
    use ApiResponse;

    /**
     * 手机登录
     * @param RequestInterface $request
     * @return array|\Psr\Http\Message\ResponseInterface
     */
    public function login(RequestInterface $request)
    {
        $logic = make(UserLoginLogic::class);

        if(!$logic->validate($request->all())){
            return $this->fails($logic->validator);
        }
        $token = $logic->login();

        return $this->success([ "token" => $token,]);
    }

    /**
     * 手机号码检测
     * @param RequestInterface $request
     * @return array
     */
    public function check(RequestInterface $request)
    {
        $validator = $this->container->get(ValidatorFactory::class)->make($request->all(),[
            "phone" => "required",
        ]);

        if($validator->fails()){
            return $this->fails($validator);
        }
        $params = $validator->validated();

        $result = make(UserLoginServiceInterface::class)->phoneLoginCheck($params["phone"]);

        return $this->success([
            "check" => $result,
        ]);
    }

    /**
     * 发送手机验证码
     * @param RequestInterface $request
     * @return array
     */
    public function code(RequestInterface $request)
    {
        $validator = $this->container->get(ValidatorFactory::class)->make($request->all(),[
            "phone" => "required",
        ]);

        if($validator->fails()){
            return $this->fails($validator);
        }
        $params = $validator->validated();

        $result = make(UserLoginServiceInterface::class)->sendLoginPhoneCode($params["phone"]);

        return $this->success([
            "send_at" => $result ? time() : 0 ,
        ]);
    }
}
